package com.bbs.web.controller;

import com.bbs.domain.User;
import com.bbs.entity.Result;
import com.bbs.service.LoginService;
import com.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(String username,String password, HttpSession session){

        if (username==null||password==null){
            return new Result(1,"账户或密码不能为空");
        }
        User loginUser = loginService.login(username, password);
        if (loginUser==null){
            return new Result(1,"用户不存在");
        }
        session.setAttribute("user",loginUser);
        loginService.changeStatus(loginUser);
        return new Result(0,"用户成功登陆");

    }

    /****
     * 用户注册
     */
    @PostMapping("/regist")
    public Result regist (@RequestBody User user, HttpServletRequest request) {
        System.out.println(user);
        //调用userService的方法查询得到user对象
        Result result = userService.userRegister(user);
        if (result.getCode()==0){
            //注册成功，将用户名存入session
            request.getSession().setAttribute("username",user.getUsername());
        }
        return result;

    }

    /**
     * 从session中取出用户名
     * @param request
     * @return
     */
    @GetMapping("/showUsername")
    public String showUsername(HttpServletRequest request){
        return (String)request.getSession().getAttribute("username");
    }

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return
     */
    @GetMapping("/findUserByUsername")
    public Result findUserByUsername(String username){

        User user = userService.findUserByUsername(username);
        if (user!=null){
            return new Result(1,"用户名已存在");
        }
        return new Result(0,"用户名不存在");
    }
}
